using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Web.UI;

using Pampa.CRUD.Core;
using Pampa.CRUD.Exceptions;
using Pampa.CRUD.UI.CustomControls;
using Pampa.CRUD.Configuration.Validations;

namespace Pampa.CRUD.Configuration
{
    /// <summary>
    /// Esta clase representa la definicion de un combo estatico en el ABM de una entidad
    /// </summary>
    public class EntitySelectorItem : EntityAbstractItem
    {
        int size;
        bool active;

        EntitySelector entitySelector = new EntitySelector();

        public EntitySelectorItem() : base()
        {
            size = 5;
            active = true;

            this.MinimumInputLength = 2;
        }

        public EntitySelectorItem(EntitySelectorItem sourceItem) : base(sourceItem)
        {
            this.Size = sourceItem.Size;
            this.Active = sourceItem.Active;
            this.Multiple = sourceItem.Multiple;
            this.EmptyText = sourceItem.EmptyText;
            this.PropertyId = sourceItem.PropertyId;
            this.PropertyDescription = sourceItem.PropertyDescription;
        }

        #region Properties

        public int Size
        {
            get { return size; }
            set { size = value; }
        }
        
        public bool Active
        {
            get { return active; }
            set { active = value; }
        }

        public bool Multiple
        {
            get;
            set;
        }

        public string EmptyText
        {
            get;
            set;
        }

        public int MinimumInputLength
        {
            get;
            set;
        }

        public override ItemType ItemType
        {
            get { return ItemType.Selector; }
        }

        public override Control Control
        {
            get
            {
                entitySelector.Width = this.ValueWidth;
                entitySelector.EntityName = this.EntityName;
                entitySelector.ForeingProperty = this.ForeingProperty;
                entitySelector.CssClass = "selector";
                entitySelector.OnClientSelect = this.OnClientChange;
                entitySelector.OnClientUnselect = this.OnClientChange;
                entitySelector.Enabled = this.Enabled;
                entitySelector.Size = this.Size;
                entitySelector.Active = this.Active;
                entitySelector.Multiple = this.Multiple;
                entitySelector.EmptyText = this.EmptyText;
                entitySelector.MinimumInputLength = this.MinimumInputLength;
                entitySelector.PropertyId = this.PropertyId;
                entitySelector.PropertyDescription = this.PropertyDescription;

                if (this.Value != null)
                {
                    entitySelector.Value = GetStringValue();
                    entitySelector.Description = GetStringDescription();
                }

                return entitySelector;
            }
        }

        #endregion

        #region Public Functions

        public override VisibleItem Clone()
        {
            return new EntitySelectorItem(this);
        }

        public override void LoadXml(XmlNode node)
        {
            try
            {
                base.LoadXml(node);

                if (node.Attributes["Size"] != null)
                    this.Size = int.Parse(node.Attributes["Size"].Value);

                if (node.Attributes["Active"] != null)
                {
                    string strActive = node.Attributes["Active"].Value;
                    bool isActive;
                    if (bool.TryParse(strActive, out isActive))
                    {
                        Active = isActive;                    
                    }
                }

                if (node.Attributes["Multiple"] != null)
                {
                    string strMultiple = node.Attributes["Multiple"].Value;
                    bool isMultiple;
                    if (bool.TryParse(strMultiple, out isMultiple))
                    {
                        this.Multiple = isMultiple;
                    }
                }

                if (node.Attributes["EmptyText"] != null)
                    this.EmptyText = node.Attributes["EmptyText"].Value;

                if (node.Attributes["PropertyId"] != null)
                    this.PropertyId = node.Attributes["PropertyId"].Value;

                if (node.Attributes["PropertyDescription"] != null)
                    this.PropertyDescription = node.Attributes["PropertyDescription"].Value;   
            }
            catch (Exception ex)
            {
                throw new Pampa.CRUD.Exceptions.ConfigurationException("Item " + this.Id + " is not well defined.", ex);
            }
        }

        #endregion

        #region Private functions

        private string GetStringValue()
        {
            if(this.Value is IList)
            {
                var list = (IList) this.Value;
                var values = (from object value in list select GetStringValue(value)).ToList();
                return string.Join(",", values);
            }
            else
            {
                return GetStringValue(this.Value);
            }
        }

        private string GetStringDescription()
        {
            if (this.Value is IList)
            {
                var list = (IList)this.Value;
                var descs = (from object value in list select GetStringDescription(value)).ToList();
                return string.Join(",", descs);
            }
            else
            {
                return GetStringDescription(this.Value);
            }
        }

        private string GetStringValue(object value)
        {
            string strValue = "";

            if (value != null)
            {
                if (value is IIdDescription)
                {
                    strValue = ((IIdDescription)value).Id;
                }
                else if (value.GetType().IsEnum)
                {
                    strValue = ((int)value).ToString();
                }
                else if (!string.IsNullOrEmpty(this.PropertyId))
                {
                    try
                    {
                        strValue = EntityManager.GetPropertyValue(value, this.PropertyId).ToString();
                    }
                    catch (EntityManagerException)
                    {
                        strValue = value.ToString();
                    }
                }
                else
                {
                    strValue = value.ToString();
                }
            }

            return strValue;
        }

        protected string GetStringDescription(object value)
        {
            string description;

            if (value is IIdDescription)
            {
                description = ((IIdDescription)value).Description.Trim();
            }
            else if (!string.IsNullOrEmpty(this.PropertyDescription))
            {
                try
                {
                    description = EntityManager.GetPropertyValue(value, this.PropertyDescription).ToString();
                }
                catch (EntityManagerException)
                {
                    description = value.ToString();
                }
            }
            else
            {
                description = value.ToString();
            }

            return description;
        }

        #endregion
    }
}
